package cn.lbaicai.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.lbaicai.common.CurrentUser;
import cn.lbaicai.core.BaseController;
import cn.lbaicai.entity.ResultData;
import cn.lbaicai.entity.Role;
import cn.lbaicai.entity.User;
import cn.lbaicai.entity.Userrole;
import cn.lbaicai.service.RoleService;
import cn.lbaicai.service.RoleUserService;
import cn.lbaicai.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleUserService roleUserService;
	//用户列表
	@RequestMapping("/list")
	public String list(){
		return "user/list";
	}
	//用户信息
	@RequestMapping("/userData")
	@ResponseBody
	public String userData(@CurrentUser User user,int page,int limit,String username,String startTime,String endTime){
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("page",page);
		paramMap.put("limit",limit);
		if(StringUtils.isNotBlank(username))
			paramMap.put("username",username);
		if(StringUtils.isNotBlank(startTime))
			paramMap.put("startTime",startTime);
		if(StringUtils.isNotBlank(endTime))
			paramMap.put("endTime",endTime);
		ResultData<List<User>> resultData = userService.selectByMap(paramMap);
		//userService
		return JSON.toJSONString(resultData);
	}
	@RequestMapping("/saveUser")
	public String saveUser(int id,Model model){
		User user = new User();
		if(id>0){
			user = userService.selectByPrimaryKey(id);
		}
		List<Role> lRole = roleService.selectByRole(new Role());
		List<Userrole> userRole = roleUserService.selectByUid(id);
		model.addAttribute("userRole", userRole);
		model.addAttribute("roles", lRole);
		model.addAttribute("user", user);
		return "/user/saveUser";
	}
	@RequestMapping("/updateUser")
	@ResponseBody
	public String updateUser(HttpServletRequest request,@RequestParam(value="roles[]",required = false) String[] roles[]){
		String username = request.getParameter("username");
		String nick = request.getParameter("nick");
		String phone = request.getParameter("phone");
		//String roles = request.getParameter("roles");
		String[] roless = request.getParameterValues("roles[]");
		return "";
	}
}
